package com.chushouya.order.service.admin.impl;

import com.general.framework.core.exception.Ex;
import com.chushouya.manager.service.common.BonusVerificationService;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.service.admin.OrderBonusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * 订单红包服务实现
 * 
 * @author chushouya
 * @date 2025-08-13
 */
@Slf4j
@Service
public class OrderBonusServiceImpl implements OrderBonusService {
    
    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;
    
    @Resource
    private BonusVerificationService bonusVerificationService;

    private OrderEntity getOrderEntity(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if(Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在 - 订单ID: {}", orderId);
        }
        return orderEntity;
    }

    private OrderExtendEntity getOrderExtendEntity(Long orderId) {
        OrderExtendEntity orderExtendEntity = orderExtendRepository.selectByOrderId(orderId);
        if(Objects.isNull(orderExtendEntity)) {
            throw Ex.business("订单扩展信息不存在 - 订单ID: {}", orderId);
        }
        return orderExtendEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderBonusPrice(Long orderId, BigDecimal bonusPrice) {
        try {
            OrderEntity orderEntity = getOrderEntity(orderId);
            OrderEntity update = new OrderEntity();
            update.setOrderId(orderId);
            update.setBonusPrice(bonusPrice);
            update.setUpdateTime(new Date());
            update.setOrderPrice(orderEntity.getOrderPrice().add(bonusPrice));
            orderRepository.updateByPrimaryKeySelective(update);
            return true;
        } catch (Exception e) {
            log.error("更新订单红包金额失败 - 订单ID: {}, 红包金额: {}, 错误: {}", 
                    orderId, bonusPrice, e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processOrderBonusVerification(Long orderId) {
        try {
            log.info("开始处理订单红包核销 - 订单ID: {}", orderId);
            
            // 查询订单信息
            OrderEntity orderEntity = getOrderEntity(orderId);
            OrderExtendEntity orderExtendEntity = getOrderExtendEntity(orderId);
            
            // 示例逻辑（需要根据实际情况调整）:
             Long userId = orderEntity.getUserId(); // 需要确认OrderEntity是否有userId字段
             Long bonusId = orderExtendEntity.getBonusId(); // 需要确认OrderEntity是否有bonusId字段
             BigDecimal bonusPrice = orderExtendEntity.getBonus(); // 已存在
             BigDecimal evaluatePrice = orderEntity.getEvaluatePrice(); // 已存在
            
            // 检查订单是否有红包信息
            if (bonusPrice == null || bonusPrice.compareTo(BigDecimal.ZERO) <= 0) {
                log.debug("订单无红包信息，跳过核销 - 订单ID: {} {}", orderId, bonusPrice);
                return;
            }
            
            // 检查评估价格
            if (evaluatePrice == null || evaluatePrice.compareTo(BigDecimal.ZERO) <= 0) {
                log.warn("订单评估价格无效，跳过红包核销 - 订单ID: {}, 评估价格: {}", 
                        orderId, evaluatePrice);
                return;
            }
            
            log.info("订单红包核销处理逻辑待完善 - 订单ID: {}, 红包金额: {}, 评估价格: {}", 
                    orderId, bonusPrice, evaluatePrice);
            
             BigDecimal bonusAmount = bonusVerificationService.verifyBonus(
                     orderId,
                     userId,
                     bonusId,
                     bonusPrice,
                     evaluatePrice
             );
            
            // 更新订单红包金额（如果需要的话）
             if (bonusAmount.compareTo(BigDecimal.ZERO) > 0) {
                 updateOrderBonusPrice(orderId, bonusAmount);
                 log.info("订单红包核销成功 - 订单ID: {}, 核销金额: {}", orderId, bonusAmount);
             }
            
        } catch (Exception e) {
            log.error("订单红包核销处理异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw e;
        }
    }
}
